package org.jeecg.modules.contract.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.contract.entity.ContractFile;
import org.jeecg.modules.contract.entity.ContractFileEnum;
import org.jeecg.modules.contract.entity.ContractManagement;
import org.jeecg.modules.contract.mapper.ContractManagementMapper;
import org.jeecg.modules.contract.service.IContractFileService;
import org.jeecg.modules.contract.service.IContractManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: 合同管理
 * @Author: jeecg-boot
 * @Date: 2019-07-29
 * @Version: V1.0
 */
@Service
public class ContractManagementServiceImpl extends ServiceImpl <ContractManagementMapper, ContractManagement> implements IContractManagementService {

    @Autowired
    private IContractFileService iContractFileService;
    @Value("${jeecg.path.upload}")
    private String uploadPath;

    /**
     * 上传文件
     *
     * @param fileMap
     * @return
     */
    @Override
    public Result getFileUrl(Map <String, MultipartFile> fileMap) {
        if (fileMap != null) {
            ContractFile contractFile;
            for (Map.Entry <String, MultipartFile> fileEntry : fileMap.entrySet()) {
                MultipartFile file=fileEntry.getValue();
                // 获取文件名
                String filename=file.getOriginalFilename();
                // 时间轴
                String timTemp=String.valueOf(DateUtils.getMillis());
                // 文件大小
                long size=file.getSize();
                // 临时存储
                String tempFileName=timTemp + filename;
                File file1=new File(uploadPath + ContractFileEnum.CONTRACT_FILE.getFile());
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                // 文件保存实体类
                String id=UUID.randomUUID().toString();
                contractFile=new ContractFile();
                contractFile.setFileSize(size);
                contractFile.setFileName(filename);
                contractFile.setFileSaveName(timTemp + filename);
                contractFile.setFilePath(uploadPath + ContractFileEnum.CONTRACT_FILE.getFile() + "/" + tempFileName);
                contractFile.setPkFile(id);
                try {
                    file.transferTo(new File(uploadPath + ContractFileEnum.CONTRACT_FILE.getFile() + "/" + tempFileName));
                    // work 转 pdf
                    // this.savePDF(timTemp,filename);
                } catch (Exception e) {
                    return Result.error(e.getMessage());
                }

                iContractFileService.save(contractFile);
                return Result.ok(id);
            }
        }
        return Result.ok();
    }

    /**
     * 根据类型转换Work
     *
     * @param byId
     * @param req
     * @return
     */
    @Override
    public File transitionWord(ContractManagement byId, HttpServletRequest req) throws IOException, TemplateException {

        // 根据类型 获取模板并导出
        String ftlName="";
        switch (byId.getContractType() == null ? 1 : byId.getContractType()) {
            case 1:
                ftlName="dingjin.ftl";
                break;
            case 2:
                ftlName="gongyu.ftl";
                break;
            case 3:
                ftlName="zhengzu.ftl";
                break;
            default:
                break;
        }
        Resource resource=new ClassPathResource("/contract");
        File sourceFile=resource.getFile();
        Configuration configuration=new Configuration();
        configuration.setDirectoryForTemplateLoading(sourceFile);
        Template template=configuration.getTemplate(ftlName);

        Map <String, Object> jsonObject=(Map <String, Object>) JSON.parseObject(JSON.toJSONString(byId,SerializerFeature.WriteNullStringAsEmpty));
        String value=String.valueOf(DateUtils.getMillis());
        //导出文件
        File outFile=new File(uploadPath + "/" +value + ".docx");
        Writer out=null;
        out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

        template.process(jsonObject, out);
        out.close();
        return outFile;
    }


}
